﻿using Abp.Domain.Repositories;
using MyCompanyName.AbpZeroTemplate.Prm.Document.Dto;
using MyCompanyName.AbpZeroTemplate.Prm.Project;
using MyCompanyName.AbpZeroTemplate.Prm.Admin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Abp.AutoMapper;
using System.Threading.Tasks;
using System.IO;
using System.Web;
using MyCompanyName.AbpZeroTemplate.Prm.Authorization;
using Abp.Domain.Uow;
using Abp.Runtime.Session;
using Abp.Net.Mail;
using Abp.Application.Services.Dto;

namespace MyCompanyName.AbpZeroTemplate.Prm.Document
{
    public class DocumentAppService : AbpZeroTemplateAppServiceBase, IDocumentAppService
    {
        private readonly ProjectManager projectManager;
        private readonly OperationLogManager operationLogManager;
        private readonly IRepository<DocumentType> documentTypeRepository;
        //private readonly IRepository<Tag> tagRepository;
        private readonly MailManager mailManagerRepository;
        private readonly PermissionService permissionService;
        private readonly IUnitOfWorkManager unitManager;
        private readonly IRepository<ProjectDocmeutShare> projectDocmeutShareRepository;
        private readonly IRepository<ProjectDocmeutShareMember> projectDocmeutShareMemberRepository;
        //private readonly IEmailSender _emailSender;

        public DocumentAppService(
            ProjectManager _projectManager,
            IRepository<DocumentType> _documentTypeRepository,
            OperationLogManager _operationLogManager,
            PermissionService _permissionService,
            MailManager _mailManagerRepository,
            //IRepository<Tag> _tagRepository,
            IEmailSender emailSender,
            IUnitOfWorkManager _unitManager,

        IRepository<ProjectDocmeutShare> _projectDocmeutShareRepository,
        IRepository<ProjectDocmeutShareMember> _projectDocmeutShareMemberRepository
            )
        {
            unitManager = _unitManager;
            projectManager = _projectManager;
            // tagRepository = _tagRepository;
            mailManagerRepository = _mailManagerRepository;
            operationLogManager = _operationLogManager;
            documentTypeRepository = _documentTypeRepository;
            permissionService = _permissionService;
            projectDocmeutShareRepository = _projectDocmeutShareRepository;
            projectDocmeutShareMemberRepository = _projectDocmeutShareMemberRepository;
        }



        /// <summary>
        /// 文档类型树
        /// </summary>
        /// <returns></returns>
        public List<GetDocumentCheckedTreeDto> GetDocumentTree(int projectId)
        {
            var types = documentTypeRepository.GetAll().OrderBy(x => x.OrderNo).Where(x => x.IsEnabled).ToList();

            var pdocs = projectManager.projectDocTypeRepository.GetAll().Where(x => x.ProjectId == projectId).ToList();

            List<GetDocumentCheckedTreeDto> result = new List<GetDocumentCheckedTreeDto>();
            var groups = types.Select(x => x.RootName).Distinct();


            int i = 1000;
            int j = 500;
            foreach (var item in groups)
            {
                i++;
                var root = new GetDocumentCheckedTreeDto();
                if (!string.IsNullOrEmpty(item))
                {
                    root.id = i.ToString();
                    root.children = new List<GetDocumentCheckedTreeDto>();
                    root.expanded = false;
                    root.@checked = false;
                    root.leaf = false;
                    root.parentId = "0";
                    root.text = item;
                    result.Add(root);
                }

                var parents = types.Where(x => x.RootName == item).Select(x => x.ParentName).Distinct();

                foreach (var p in parents)
                {
                    j++;
                    var parent = new GetDocumentCheckedTreeDto();
                    if (!string.IsNullOrEmpty(p))
                    {
                        parent.id = j.ToString();
                        parent.children = new List<GetDocumentCheckedTreeDto>();
                        parent.expanded = false;
                        parent.leaf = false;
                        parent.@checked = false;
                        parent.parentId = "0";
                        parent.text = p;
                        if (!string.IsNullOrEmpty(item))
                        {
                            parent.parentId = root.id;
                            root.children.Add(parent);
                        }
                        else
                        {
                            result.Add(parent);
                        }
                    }

                    var childs = types.Where(x => x.ParentName == p);
                    foreach (var c in childs)
                    {
                        if (!string.IsNullOrEmpty(c.Name))
                        {
                            var pdoc = pdocs.Where(x => x.DocTypeId == c.Id).SingleOrDefault();
                            var child = new GetDocumentCheckedTreeDto()
                            {
                                id = c.Id.ToString(),
                                children = null,
                                expanded = true,
                                leaf = true,
                                @checked = false,
                                defaultUploadNum = c.DefaultUploadNum,
                                parentId = "0",
                                text = c.Name
                            };
                            if (pdoc != null)
                            {
                                child.@checked = true;
                                child.defaultUploadNum = pdoc.UploadNum;
                            }
                            if (!string.IsNullOrEmpty(p))
                            {
                                child.parentId = parent.id;
                                parent.children.Add(child);
                            }
                            else
                            {
                                result.Add(child);
                            }
                        }
                    }
                }
            }
            //var json = result.Where(x => x.parentId == "0").ToList();

            return result.Where(x => x.parentId == "0").ToList();
        }

        public async Task SetProjectDocumentType(SetProjectDocumentTypeInPut input)
        {
            var projectId = int.Parse(input.ProjectId);
            await projectManager.projectDocTypeRepository.DeleteAsync(x => x.ProjectId == projectId);

            List<KeyValuePair<int, int>> keys = Newtonsoft.Json.JsonConvert.DeserializeObject<List<KeyValuePair<int, int>>>(input.Types);
            foreach (var item in keys)
            {
                projectManager.projectDocTypeRepository.Insert(new ProjectDocType()
                {
                    ProjectId = projectId,
                    DocTypeId = item.Key,
                    UploadNum = item.Value
                });
            }
            await operationLogManager.Create(projectId, "项目文档上传类型设置", HostOperation.项目, Newtonsoft.Json.JsonConvert.SerializeObject(input));
        }


        public List<GetDocumentTreeDto> GetProjectDocumentTree(int projectId)
        {

            var userId = AbpSession.GetUserId();
            var docTypes = projectManager.projectDocTypeRepository
                .GetAll()
                .Where(x => x.ProjectId == projectId)
                .ToList();

            var ids = docTypes.Select(q => q.DocTypeId);
            var types = documentTypeRepository
                .GetAll()
                .Where(x => ids.Any(m => m == x.Id))
                .OrderBy(x => x.OrderNo)
                .ToList();

            //types.Select(x=>x.DefaultUploadNum>1)

            List<GetDocumentTreeDto> result = new List<GetDocumentTreeDto>();
            var groups = types.Select(x => x.RootName).Distinct();


            int i = 1000;
            int j = 500;

            var 项目文档 = new GetDocumentTreeDto()
            {
                id = (-1).ToString(),
                children = new List<GetDocumentTreeDto>(),
                expanded = false,
                leaf = false,
                parentId = "0",
                defaultUploadNum = docTypes.Sum(x => x.UploadNum),
                trashNum = projectManager.projectDocmeutRepository.Count(x => x.ProjectId == projectId && x.DocTypeId > 0 && x.IsDeleted),
                uploadedNum = -1,
                text = "项目文档"
            };
            result.Add(项目文档);

            foreach (var item in groups)
            {
                i++;
                var root = new GetDocumentTreeDto();
                if (!string.IsNullOrEmpty(item))
                {
                    root.id = i.ToString();
                    root.children = new List<GetDocumentTreeDto>();
                    root.expanded = false;
                    root.leaf = false;
                    root.trashNum = 0;
                    root.parentId = 项目文档.id;
                    root.defaultUploadNum = 0;
                    root.uploadedNum = -1;
                    root.text = item;
                    result.Add(root);
                    项目文档.children.Add(root);
                }

                var parents = types.Where(x => x.RootName == item).Select(x => x.ParentName).Distinct();

                foreach (var p in parents)
                {
                    j++;
                    var parent = new GetDocumentTreeDto();
                    if (!string.IsNullOrEmpty(p))
                    {
                        parent.id = j.ToString();
                        parent.children = new List<GetDocumentTreeDto>();
                        parent.expanded = false;
                        parent.leaf = false;
                        root.trashNum = 0;
                        parent.parentId = 项目文档.id;
                        parent.defaultUploadNum = 0;
                        parent.uploadedNum = -1;
                        parent.text = p;
                        if (!string.IsNullOrEmpty(item))
                        {
                            parent.parentId = root.id;
                            root.children.Add(parent);
                        }
                        else
                        {
                            项目文档.children.Add(parent);
                        }
                        result.Add(parent);
                    }

                    var childs = types.Where(x => x.ParentName == p);
                    foreach (var c in childs)
                    {
                        if (!string.IsNullOrEmpty(c.Name))
                        {
                            var dto = docTypes.Where(x => x.DocTypeId == c.Id).SingleOrDefault();
                            var child = new GetDocumentTreeDto()
                            {
                                id = c.Id.ToString(),
                                children = null,
                                expanded = true,
                                leaf = true,
                                trashNum = projectManager.projectDocmeutRepository.Count(x => x.ProjectId == projectId && x.DocTypeId == c.Id && x.IsDeleted),
                                parentId = 项目文档.id,
                                uploadedNum = GetDocumentNum(c.Id, projectId), //projectManager.projectDocmeutRepository.GetAll().Where(x => x.ProjectId == projectId && x.DocTypeId == c.Id).Count(),
                                text = c.Name,
                                defaultUploadNum = dto.UploadNum
                            };
                            if (c.DefaultUploadNum > 1)
                            {
                                var ccChildCount = projectManager.projectDocmeutRepository.GetAll()
                                    .Where(x => x.ProjectId == projectId && x.DocTypeId == c.Id && !x.IsDeleted).Count();
                                var ccChildNames = projectManager.projectDocmeutRepository.GetAll()
                                   .Where(x => x.ProjectId == projectId && x.DocTypeId == c.Id && !x.IsDeleted)
                                   .Select(t => t.StepName).Distinct().ToList();
                                if (ccChildCount > 0 && ccChildNames.Count > 0)
                                {
                                    child.children = new List<GetDocumentTreeDto>();
                                    child.leaf = false;
                                    if (!ccChildNames.Contains("Default"))
                                    {
                                        ccChildNames.Add("Default");
                                    }
                                    int index = 1;
                                    foreach (var _cchildName in ccChildNames)
                                    {
                                        if (!string.IsNullOrEmpty(_cchildName))
                                        {
                                            int trashNum = 0;
                                            int uploadNum = 0;
                                            if (_cchildName.Equals("Default"))
                                            {
                                                using (unitManager.Current.DisableFilter(AbpDataFilters.SoftDelete))
                                                {

                                                    trashNum = projectManager.projectDocmeutRepository.GetAll().Where(x => x.ProjectId == projectId && x.DocTypeId == c.Id && (x.StepName == _cchildName || x.StepName == "") && x.IsDeleted == true).Count();
                                                    uploadNum = projectManager.projectDocmeutRepository.GetAll()
                                                        .Where(x => x.ProjectId == projectId && x.DocTypeId == c.Id && (x.StepName == _cchildName || x.StepName == "") && x.IsDeleted == false).Count();
                                                }
                                            }
                                            else
                                            {
                                                using (unitManager.Current.DisableFilter(AbpDataFilters.SoftDelete))
                                                {
                                                    trashNum = projectManager.projectDocmeutRepository.GetAll().Where(x => x.ProjectId == projectId && x.DocTypeId == c.Id && (x.StepName == _cchildName) && x.IsDeleted == true).Count();
                                                    uploadNum = projectManager.projectDocmeutRepository.Count(x => x.ProjectId == projectId && x.DocTypeId == c.Id && x.StepName == _cchildName && x.IsDeleted == false);
                                                }
                                            }

                                            var cchild = new GetDocumentTreeDto()
                                            {
                                                children = null,
                                                expanded = true,
                                                leaf = true,
                                                trashNum = trashNum,
                                                defaultUploadNum = 1,
                                                id = string.Format("{0}_{1}", child.id, _cchildName),
                                                parentId = child.id,
                                                text = _cchildName,
                                                uploadedNum = uploadNum
                                            };
                                            child.children.Add(cchild);
                                        }

                                        index++;
                                    }



                                }
                            }

                            if (child.uploadedNum == 0 && !permissionService.HasPermission(projectId, userId, c.Id, DocmentFunctions.文档查看))
                            {
                                continue;
                            }

                            if (!string.IsNullOrEmpty(p))
                            {
                                child.parentId = parent.id;
                                parent.children.Add(child);
                            }
                            else
                            {
                                项目文档.children.Add(child);
                            }
                            result.Add(child);
                        }
                    }
                }
            }


            List<GetDocumentTreeDto> removeNodes = new List<GetDocumentTreeDto>();
            do
            {
                removeNodes = new List<GetDocumentTreeDto>();
                var _result = result.Where(x => x.uploadedNum < 0);
                foreach (var item in _result)
                {
                    if (item.children != null && item.children.Count > 0 && !item.children.Any(x => x.uploadedNum < 0))
                    {
                        item.uploadedNum = item.children.Sum(x => x.uploadedNum);
                        item.trashNum = item.children.Sum(x => x.trashNum);
                        item.defaultUploadNum = item.children.Sum(x => x.defaultUploadNum);
                    }
                    else if (item.children.Count == 0 && item.uploadedNum < 0)
                    {
                        removeNodes.Add(item);
                    }
                }
                List<string> removeIds = removeNodes.Select(x => x.id).ToList();
                foreach (var removeId in removeIds)
                {
                    var node = result.Where(x => x.id == removeId).FirstOrDefault();
                    var parent = result.Where(x => x.id == node.parentId).FirstOrDefault();
                    if (parent == null)
                    {
                        node.uploadedNum = 0;
                    }
                    else
                    {
                        parent.children.Remove(node);
                        result.Remove(node);
                    }
                }
            }
            while (result.Any(x => x.uploadedNum < 0));
            //var json = result.Where(x => x.parentId == "0").ToList();

            return result.Where(x => x.parentId == "0").ToList();
        }

        public List<GetDocumentOutPut> GetWeekDocument(List<int> projectIds)
        {

            var weekDocTypes = documentTypeRepository.GetAll().Where(x => x.Name.Contains("周报")).Select(x => x.Id);
            var result = projectManager.projectDocmeutRepository.GetAll()
                .Where(x => projectIds.Contains(x.ProjectId) && !x.IsDeleted && weekDocTypes.Contains(x.DocTypeId)).ToList();
            List<GetDocumentOutPut> outPut = new List<GetDocumentOutPut>();

            foreach (var item in result)
            {
                var put = new GetDocumentOutPut()
                {
                    CreationTime = item.CreationTime,
                    CreationUser = item.CreationUser,
                    proId = item.ProjectId,
                    CreatorUserId = (long)item.CreatorUserId,
                    Extension = item.Extension,
                    ReportDate = item.ReportDate,
                    FullUrl = item.FullUrl,
                    Id = item.Id,
                    Tags = item.Tags,
                    IsFixedVersion = item.IsFixedVersion,
                    Length = item.Length,
                    Name = item.Name
                };
                outPut.Add(put);
            }
            return outPut;
        }

        public List<GetDocumentOutPut> GetWeekDocument()
        {
            var weekDocTypes = documentTypeRepository.GetAll().Where(x => x.Name.Contains("周报")).Select(x => x.Id);
            var result = projectManager.projectDocmeutRepository.GetAll()
                .Where(x => !x.IsDeleted && weekDocTypes.Contains(x.DocTypeId)).ToList();
            List<GetDocumentOutPut> outPut = new List<GetDocumentOutPut>();

            foreach (var item in result)
            {
                var put = new GetDocumentOutPut()
                {
                    CreationTime = item.CreationTime,
                    CreationUser = item.CreationUser,
                    CreatorUserId = (long)item.CreatorUserId,
                    Extension = item.Extension,
                    ReportDate = item.ReportDate,
                    FullUrl = item.FullUrl,
                    Id = item.Id,
                    Tags = item.Tags,
                    IsFixedVersion = item.IsFixedVersion,
                    Length = item.Length,
                    Name = item.Name
                };
                outPut.Add(put);
            }
            return outPut;
        }
        public PagedResultOutput<GetDocumentOutPut> GetDocument(int typeId, string stepname, int projectId, bool isDelete, string documentName, string tag, int createId = 0, bool hasAuth = true,
                                                    int start = 0, int limit = 25)
        {
            var userId = AbpSession.GetUserId();
            List<ProjectDocmeut> result = new List<ProjectDocmeut>();
            var shareDocIds = new List<int>();

            DateTime dtNow = DateTime.Now.Date;
            using (unitManager.Current.DisableFilter(AbpDataFilters.SoftDelete))
            {
                var qs = projectManager.projectDocmeutRepository.GetAll().Where(x => x.ProjectId == projectId && x.IsDeleted == isDelete);
                // -1取所有项目文档 0为项目附件
                if (typeId >= 0)
                {
                    qs = qs.Where(x => x.DocTypeId == typeId);
                }
                if (!string.IsNullOrEmpty(tag))
                {
                    qs = qs.Where(x => x.Tags.Contains(tag));
                }
                if (createId > 0)
                {
                    qs = qs.Where(x => x.CreatorUserId == createId);
                }
                if (!string.IsNullOrEmpty(documentName))
                {
                    qs = qs.Where(x => x.Name.Contains(documentName));
                }

                if (!string.IsNullOrEmpty(stepname))
                {
                    if (stepname.Equals("Default"))
                    {
                        qs = qs.Where(x => x.StepName == stepname || x.StepName == "");
                    }
                    else
                    {
                        qs = qs.Where(x => x.StepName == stepname);
                    }
                }

                result = qs.OrderByDescending(x => x.ReportDate).ThenByDescending(x => x.Id).ToList();

                //获取分享给我的文档
                var docIds = qs.Select(x => x.Id);
                shareDocIds = projectManager.projectDocmeutShareMemeberRepository.GetAll()
                    .Where(x => docIds.Contains(x.DocShare.Doc.Id) && x.UserId == userId && x.DocShare.EndDate >= dtNow)
                    .Select(x => x.DocShare.ProjectDocId).ToList();

                if (hasAuth)
                {
                    result = result.Where(x => shareDocIds.Contains(x.Id) || permissionService.HasPermission(projectId, userId, x.DocTypeId, DocmentFunctions.文档查看)).ToList();
                }
            }

            int count = result.Count;
            result = result.OrderByDescending(x => x.ReportDate).ThenByDescending(x => x.Id).Skip(start).Take(limit).ToList();

            List<GetDocumentOutPut> outPut = new List<GetDocumentOutPut>();
            int rowIndex = 1;

            bool HasDelete = permissionService.HasPermission(projectId, userId, typeId, DocmentFunctions.文档删除);
            bool HasDownLoad = permissionService.HasPermission(projectId, userId, typeId, DocmentFunctions.文档下载);
            bool HasEdit = permissionService.HasPermission(projectId, userId, typeId, DocmentFunctions.文档编辑);
            bool HasViewVersion = permissionService.HasPermission(projectId, userId, typeId, DocmentFunctions.文档版本查看);
            bool HasFixedVersion = permissionService.HasPermission(projectId, userId, typeId, DocmentFunctions.文档定版);
            bool HasShare = permissionService.HasPermission(projectId, userId, typeId, DocmentFunctions.文档分享);
            bool HasLogView = permissionService.HasPermission(projectId, userId, typeId, DocmentFunctions.文档日志查看);

            foreach (var item in result)
            {
                var put = new GetDocumentOutPut()
                {
                    row = rowIndex++,
                    CreationTime = item.CreationTime,
                    CreationUser = item.CreationUser,
                    ReportDate = item.ReportDate,
                    Extension = item.Extension,
                    FullUrl = item.FullUrl,
                    Id = item.Id,
                    Tags = item.Tags,
                    IsFixedVersion = item.IsFixedVersion,
                    Length = item.Length,
                    Name = item.Name,
                    IsDelete = item.IsDeleted,
                    VersionNo = item.VersionNo,
                    HasShared = projectManager.projectDocmeutShareMemeberRepository.GetAll().Any(x => x.DocShare.ProjectDocId == item.Id && x.DocShare.EndDate >= dtNow),
                    HasDelete = item.DocTypeId == 0 ? (item.CreatorUserId == userId ? true : false) : HasDelete,
                    HasDownLoad = shareDocIds.Contains(item.Id) || HasDownLoad,
                    HasEdit = HasEdit,
                    HasViewVersion = HasViewVersion,
                    HasFixedVersion = HasFixedVersion,
                    HasShare = HasShare,
                    HasLogView = HasLogView,
                };
                outPut.Add(put);
            }
            return new PagedResultOutput<GetDocumentOutPut>(count, outPut);
        }



        public int GetDocumentNum(int typeId, int projectId)
        {
            var userId = AbpSession.GetUserId();
            var shareDocIds = new List<int>();

            DateTime dtNow = DateTime.Now.Date;
            using (unitManager.Current.DisableFilter(AbpDataFilters.SoftDelete))
            {
                var qs = projectManager.projectDocmeutRepository.GetAll().Where(x => x.ProjectId == projectId && x.DocTypeId == typeId && x.IsDeleted == false);
                //获取分享给我的文档
                var docIds = qs.Select(x => x.Id);
                shareDocIds = projectManager.projectDocmeutShareMemeberRepository.GetAll().Where(x => docIds.Contains(x.DocShare.Doc.Id) && x.UserId == userId && x.DocShare.EndDate >= dtNow).Select(x => x.DocShare.ProjectDocId).ToList();
                var lst = qs.ToList();
                return lst.Where(x => shareDocIds.Contains(x.Id) || permissionService.HasPermission(projectId, userId, x.DocTypeId, DocmentFunctions.文档查看)).Count();
            }
        }



        [UnitOfWork(isTransactional: false)]
        public async Task UploadDocument()
        {
            var typeId = HttpContext.Current.Request.Form["TypeId"];
            var projectId = HttpContext.Current.Request.Form["ProjectId"];
            var fileName = HttpContext.Current.Request.Form["fileName"];
            var taskId = HttpContext.Current.Request.Form["taskId"];
            var reportDate = HttpContext.Current.Request.Form["reportDate"];
            var note = HttpContext.Current.Request.Form["note"];
            var file = HttpContext.Current.Request.Files[0];
            var userId = AbpSession.GetUserId();
            var uploadFile = new HttpPostedFileWrapper(file) as HttpPostedFileBase;
            await _UploadDocument(typeId, projectId, fileName, taskId, reportDate, note, uploadFile);
        }

        [UnitOfWork(isTransactional: false)]
        public async Task _UploadDocument(string typeId, string projectId, string fileName, string taskId, string reportDate, string note, HttpPostedFileBase file)
        {
            var userId = AbpSession.GetUserId();
            Guid fileGuid = Abp.GridFS.GridFSHelper.Upload(file, userId.ToString());
            var doc = new ProjectDocmeut()
            {
                CommitDate = DateTime.Now,
                Extension = Path.GetExtension(file.FileName),
                DocTypeId = int.Parse(typeId),
                FullUrl = fileGuid.ToString(),
                Length = file.ContentLength / 1024,
                Name = fileName,
                TaskId = string.IsNullOrEmpty(taskId) ? 0 : int.Parse(taskId),
                ProjectId = int.Parse(projectId),
                VersionNo = 0.1,
                IsFixedVersion = false,
                CreationUser = UserManager.Users.Where(x => x.Id == userId).SingleOrDefault().Name,
                Note = note,
                ReportDate = DateTime.Parse(reportDate),
                Versions = new List<ProjectDocmeutVersion>()
            };
            int id = projectManager.projectDocmeutRepository.InsertAndGetId(doc);

            projectManager.projectDocmeutVersionRepository.Insert(new ProjectDocmeutVersion()
            {
                Version = 0.1,
                CreationUser = UserManager.Users.Where(x => x.Id == userId).SingleOrDefault().Name,
                Length = file.ContentLength / 1024,
                Content = "",
                Name = fileName,
                Extension = Path.GetExtension(file.FileName),
                FullUrl = fileGuid.ToString(),
                OriginalName = file.FileName,
                ProjectDocmeutId = id,
                Note = note,
                ReportDate = DateTime.Parse(reportDate),
                TaskId = string.IsNullOrEmpty(taskId) ? 0 : int.Parse(taskId),
            });


            string str = string.Format("上传文档 {0}", doc.Name);
            await operationLogManager.Create(id, str, HostOperation.文档, Newtonsoft.Json.JsonConvert.SerializeObject(new { ProjectId = projectId, TypeId = typeId }), LogType.Doc上传);

            #region 发送文档上传邮件通知
            var projectInfo = projectManager.projectRepository.Get(int.Parse(projectId));
            var docType = documentTypeRepository.Get(int.Parse(typeId));
            var user = UserManager.Users.Where(x => x.Id == userId).FirstOrDefault();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic["项目名称"] = projectInfo.ProjectName;
            dic["项目编号"] = projectInfo.ProjectNo;
            dic["产品号"] = projectInfo.ProductNo;
            dic["操作时间"] = doc.CreationTime.ToString("yyyy-MM-dd");
            dic["操作人"] = user.Name;
            dic["文档类别"] = docType.Name;
            dic["文档名称"] = doc.Name;
            mailManagerRepository.CreateMailRecord(dic, MailCatelog.文档上传, int.Parse(projectId));
            #endregion
        }



        [UnitOfWork(isTransactional: false)]
        public async Task UploadDocuments()
        {
            var typeId = HttpContext.Current.Request.Form["TypeId"];
            var projectId = HttpContext.Current.Request.Form["ProjectId"]; ;
            var StepName = HttpContext.Current.Request.Form["StepName"];
            if (string.IsNullOrEmpty(StepName))
            {
                StepName = "Default";
            }
            var userId = AbpSession.GetUserId();
            List<string> docNames = new List<string>();
            var fileCount = HttpContext.Current.Request.Files.Count;
            for (int i = 0; i < fileCount; i++)
            {
                var _file = new HttpPostedFileWrapper(HttpContext.Current.Request.Files[i]) as HttpPostedFileBase;
                await _UploadDowumnets(_file, typeId, projectId, StepName);
            }
        }

        [UnitOfWork(isTransactional: false)]
        public async Task _UploadDowumnets(HttpPostedFileBase file, string typeId, string projectId, string StepName)
        {
            if (string.IsNullOrEmpty(StepName))
            {
                StepName = "Default";
            }
            var userId = AbpSession.GetUserId();
            List<string> docNames = new List<string>();

            Guid fileGuid = Abp.GridFS.GridFSHelper.Upload(file, AbpSession.GetUserId().ToString());

            var doc = new ProjectDocmeut()
            {
                CommitDate = DateTime.Now,
                Extension = Path.GetExtension(file.FileName),
                DocTypeId = int.Parse(typeId),
                FullUrl = fileGuid.ToString(),
                Length = file.ContentLength / 1024,
                Name = file.FileName,
                TaskId = 0,
                ProjectId = int.Parse(projectId),
                VersionNo = 0.1,
                IsFixedVersion = false,
                CreationUser = UserManager.Users.Where(x => x.Id == userId).SingleOrDefault().Name,
                StepName = StepName,
                Note = "",
                ReportDate = DateTime.Now,
                Versions = new List<ProjectDocmeutVersion>()
            };
            int id = projectManager.projectDocmeutRepository.InsertAndGetId(doc);

            projectManager.projectDocmeutVersionRepository.Insert(new ProjectDocmeutVersion()
            {
                Version = 0.1,
                CreationUser = UserManager.Users.Where(x => x.Id == userId).SingleOrDefault().Name,
                Length = file.ContentLength / 1024,
                Content = "",
                Name = file.FileName,
                Extension = Path.GetExtension(file.FileName),
                FullUrl = fileGuid.ToString(),
                OriginalName = file.FileName,
                ProjectDocmeutId = id,
                Note = "",
                StepName = StepName,
                ReportDate = doc.ReportDate,
                TaskId = 0
            });
            string str = string.Format("上传文档 {0}", doc.Name);
            await operationLogManager.Create(id, str, HostOperation.文档, Newtonsoft.Json.JsonConvert.SerializeObject(new { ProjectId = projectId, TypeId = typeId }), LogType.Doc上传);
            docNames.Add(doc.Name);

            #region 发送文档上传邮件通知
            var projectInfo = projectManager.projectRepository.Get(int.Parse(projectId));
            var docType = documentTypeRepository.Get(int.Parse(typeId));
            var user = UserManager.Users.Where(x => x.Id == userId).FirstOrDefault();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic["项目名称"] = projectInfo.ProjectName;
            dic["项目编号"] = projectInfo.ProjectNo;
            dic["产品号"] = projectInfo.ProductNo;
            dic["操作时间"] = DateTime.Now.ToString("yyyy-MM-dd");
            dic["操作人"] = user.Name;
            dic["文档类别"] = docType.Name;
            dic["文档名称"] = string.Join(",", docNames);

            mailManagerRepository.CreateMailRecord(dic, MailCatelog.文档上传, int.Parse(projectId));
            #endregion
        }


        [UnitOfWork(isTransactional: false)]
        public async Task UploadAttachment()
        {
            var projectId = HttpContext.Current.Request.Form["ProjectId"];
            var fileName = HttpContext.Current.Request.Form["fileName"];
            var note = HttpContext.Current.Request.Form["note"];
            var file = HttpContext.Current.Request.Files[0];
            var tags = HttpContext.Current.Request.Form["tags"];
            var _file = new HttpPostedFileWrapper(file) as HttpPostedFileBase;
            await _UploadAttachment(projectId, fileName, note, _file, tags);


            //  await operationLogManager.Create(int.Parse(projectId), "项目文档上传", HostOperation.项目, Newtonsoft.Json.JsonConvert.SerializeObject(new { ProjectId = projectId }));
        }

        [UnitOfWork(isTransactional: false)]
        public async Task _UploadAttachment(string projectId, string fileName, string note, HttpPostedFileBase file, string tags)
        {
            var userId = AbpSession.GetUserId();
            List<string> _tags = new List<string>();
            if (!string.IsNullOrEmpty(tags))
            {
                _tags = tags.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                _tags = _tags.Distinct().ToList();
            }

            Guid fileGuid = Abp.GridFS.GridFSHelper.Upload(file, AbpSession.GetUserId().ToString());

            var doc = new ProjectDocmeut()
            {
                CommitDate = DateTime.Now,
                Extension = Path.GetExtension(file.FileName),
                DocTypeId = 0,
                FullUrl = fileGuid.ToString(),
                Length = file.ContentLength / 1024,
                Name = fileName,
                TaskId = 0,
                Tags = string.Join("\n", _tags),
                ProjectId = int.Parse(projectId),
                VersionNo = 1,
                Note = note,
                CreationUser = UserManager.Users.Where(x => x.Id == userId).SingleOrDefault().Name,
                ReportDate = DateTime.Now,
                Versions = new List<ProjectDocmeutVersion>()
            };
            int id = projectManager.projectDocmeutRepository.InsertAndGetId(doc);

            string str = string.Format("上传文档 {0}", doc.Name);
            await operationLogManager.Create(id, str, HostOperation.文档, Newtonsoft.Json.JsonConvert.SerializeObject(new { ProjectId = projectId, TypeId = 0 }), LogType.Doc上传);
        }

        public int GetDocumentCount(int projectId)
        {
            return projectManager.projectDocmeutRepository.GetAll().Where(x => x.ProjectId == projectId && x.DocTypeId > 0).Count();
        }
        public int GetDocumentCount(int projectId, DateTime dts)
        {
            return projectManager.projectDocmeutRepository.GetAll().Where(x => x.ProjectId == projectId && x.DocTypeId > 0 && x.CreationTime >= dts).Count();
        }


        public List<GetDocumentVersionOutPut> GetDocumentVersion(int documentId)
        {
            var result = projectManager.projectDocmeutVersionRepository.GetAll().OrderByDescending(x => x.Version).Where(x => x.ProjectDocmeutId == documentId).ToList();
            var model = result.MapTo<List<GetDocumentVersionOutPut>>();
            return model;
        }


        [UnitOfWork(isTransactional: false)]
        public async Task EditDocument()
        {
            var documentId = HttpContext.Current.Request.Form["DocumentId"];

            var name = HttpContext.Current.Request.Form["name"];
            var taskId = HttpContext.Current.Request.Form["taskId"];
            var reportDate = HttpContext.Current.Request.Form["reportDate"];
            var note = HttpContext.Current.Request.Form["note"];

            var file = HttpContext.Current.Request.Files[0];

            var doc = await projectManager.projectDocmeutRepository.GetAsync(int.Parse(documentId));

            doc.IsFixedVersion = false;

            string fileGuid = doc.FullUrl;
            if (file != null)
            {
                doc.Extension = Path.GetExtension(file.FileName);
                doc.Length = file.ContentLength / 1024;
                fileGuid = Abp.GridFS.GridFSHelper.Upload(new HttpPostedFileWrapper(file) as HttpPostedFileBase, AbpSession.GetUserId().ToString()).ToString();
            }
            doc.Name = name;
            doc.TaskId = string.IsNullOrEmpty(taskId) ? 0 : int.Parse(taskId);
            doc.ReportDate = DateTime.Parse(reportDate);
            doc.Note = note;
            doc.VersionNo = doc.VersionNo + 0.01;


            projectManager.projectDocmeutVersionRepository.Insert(new ProjectDocmeutVersion()
            {
                Version = doc.VersionNo + 0.01,
                CreationUser = "debug",
                Length = file.ContentLength / 1024,
                Content = "",
                Name = name,
                TaskId = string.IsNullOrEmpty(taskId) ? 0 : int.Parse(taskId),
                ReportDate = DateTime.Parse(reportDate),
                Note = note,
                Extension = Path.GetExtension(file.FileName),
                FullUrl = fileGuid,
                OriginalName = file.FileName,
                ProjectDocmeutId = doc.Id
            });

            string str = string.Format("编辑文档 {0}", doc.Name);
            await operationLogManager.Create(int.Parse(documentId), str, HostOperation.文档, Newtonsoft.Json.JsonConvert.SerializeObject(new { ProjectId = doc.ProjectId, DocumentId = documentId }), LogType.Doc编辑);
        }

        public async Task ERemoveDocuments(List<int> documentIds)
        {
            var userId = AbpSession.GetUserId();

            foreach (var documentId in documentIds)
            {
                var doc = projectManager.projectDocmeutRepository.Get(documentId);
                int projectId = doc.ProjectId;

                bool hasDel = doc.DocTypeId == 0 ? (doc.CreatorUserId == userId ? true : false) : permissionService.HasPermission(projectId, userId, doc.DocTypeId, DocmentFunctions.文档删除);
                if (hasDel == false)
                {
                    throw new Abp.UI.UserFriendlyException("系统提示", "没有操作权限");
                }
                await projectManager.projectDocmeutRepository.DeleteAsync(documentId);
                string str = string.Format("删除文档 {0}", doc.Name);
                await operationLogManager.Create(documentId, str, HostOperation.文档, Newtonsoft.Json.JsonConvert.SerializeObject(new { ProjectId = projectId, DocumentId = documentId }), LogType.Doc删除);
            }

        }

        public async Task RemoveDocument(int documentId, int projectId)
        {
            var userId = AbpSession.GetUserId();
            var doc = projectManager.projectDocmeutRepository.Get(documentId);


            bool hasDel = doc.DocTypeId == 0 ? (doc.CreatorUserId == userId ? true : false) : permissionService.HasPermission(projectId, userId, doc.DocTypeId, DocmentFunctions.文档删除);
            if (hasDel == false)
            {
                throw new Abp.UI.UserFriendlyException("系统提示", "没有操作权限");
            }


            await projectManager.projectDocmeutRepository.DeleteAsync(documentId);

            string str = string.Format("删除文档 {0}", doc.Name);
            await operationLogManager.Create(documentId, str, HostOperation.文档, Newtonsoft.Json.JsonConvert.SerializeObject(new { ProjectId = projectId, DocumentId = documentId }), LogType.Doc删除);
        }

        [UnitOfWork(isTransactional: false)]
        public async Task GetFile(string path)
        {



            var doc = projectManager.projectDocmeutRepository.GetAll().Where(x => x.FullUrl == path).FirstOrDefault();
            if (doc != null)
            {
                string str = string.Format("下载文档 {0}", doc.Name);
                await operationLogManager.Create(doc.Id, str, HostOperation.文档, "", LogType.Doc下载);
            }
            else
            {

                var f = Abp.GridFS.GridFSHelper.Get(Guid.Parse(path));

                if (f == null)
                    return;
            }

            if (AbpSession.UserId == null || !permissionService.HasDownLoadPermission((long)AbpSession.UserId, path))
            {
                return;
            }


            Abp.GridFS.GridFSHelper.ResponseOne(Guid.Parse(path), AbpSession.GetUserId().ToString());


        }


        [UnitOfWork(isTransactional: false)]
        public async Task GetFileView(string path)
        {
            var doc = projectManager.projectDocmeutRepository.GetAll().Where(x => x.FullUrl == path).FirstOrDefault();
            if (doc != null)
            {
                string str = string.Format("在线查看文档 {0}", doc.Name);
                await operationLogManager.Create(doc.Id, str, HostOperation.文档, "", LogType.Doc查看);
            }
            else
            {
                return;
            }

            if (AbpSession.UserId == null || !permissionService.HasDownLoadPermission((long)AbpSession.UserId, path))
            {
                return;
            }


            Abp.GridFS.GridFSHelper.PreviewOne(Guid.Parse(path), AbpSession.GetUserId().ToString());

        }



        public async Task<GetDocumentOutPut> Get(int documentId)
        {
            var doc = await projectManager.projectDocmeutRepository.GetAsync(documentId);
            var model = doc.MapTo<GetDocumentOutPut>();
            return model;
        }


        public List<GetDocumentTreeDto> GetDocumentReportColumn()
        {
            var types = documentTypeRepository.GetAllList().Where(x => x.IsEnabled && !x.IsDeleted);

            List<GetDocumentTreeDto> result = new List<GetDocumentTreeDto>();
            var groups = types.Select(x => x.RootName).Distinct();


            int i = 1000;
            int j = 500;
            foreach (var item in groups)
            {
                i++;
                var root = new GetDocumentTreeDto();
                if (!string.IsNullOrEmpty(item))
                {
                    root.id = i.ToString();
                    root.children = new List<GetDocumentTreeDto>();
                    root.expanded = false;
                    root.leaf = false;
                    root.parentId = "0";
                    root.text = item;
                    result.Add(root);
                }

                var parents = types.Where(x => x.RootName == item).Select(x => x.ParentName).Distinct();

                foreach (var p in parents)
                {
                    j++;
                    var parent = new GetDocumentTreeDto();
                    if (!string.IsNullOrEmpty(p))
                    {
                        parent.id = j.ToString();
                        parent.children = new List<GetDocumentTreeDto>();
                        parent.expanded = false;
                        parent.leaf = false;
                        parent.parentId = "0";
                        parent.text = p;
                        if (!string.IsNullOrEmpty(item))
                        {
                            parent.parentId = root.id;
                            root.children.Add(parent);
                        }
                        else
                        {
                            result.Add(parent);
                        }
                    }

                    var childs = types.Where(x => x.ParentName == p);
                    foreach (var c in childs)
                    {
                        if (!string.IsNullOrEmpty(c.Name))
                        {
                            var child = new GetDocumentTreeDto()
                            {
                                id = c.Id.ToString(),
                                children = null,
                                expanded = true,
                                leaf = true,
                                parentId = "0",
                                text = c.Name
                            };
                            if (!string.IsNullOrEmpty(p))
                            {
                                child.parentId = parent.id;
                                parent.children.Add(child);
                            }
                            else
                            {
                                result.Add(child);
                            }
                        }
                    }
                }
            }
            return result.Where(x => x.parentId == "0").ToList();
        }


        [UnitOfWork(isTransactional: false)]
        public GetUploadFileOutPut UploadFile()
        {
            var file = HttpContext.Current.Request.Files[0];
            var baseFile = new HttpPostedFileWrapper(file) as HttpPostedFileBase;
            return UploadFile(baseFile);
        }

        public GetUploadFileOutPut UploadFile(HttpPostedFileBase baseFile)
        {
            Guid fileGuid = Abp.GridFS.GridFSHelper.Upload(baseFile, AbpSession.GetUserId().ToString());
            var outPut = new GetUploadFileOutPut()
            {
                Id = Guid.NewGuid().ToString(),
                Name = System.IO.Path.GetFileName(baseFile.FileName),
                Path = fileGuid.ToString(),
                Size = (baseFile.ContentLength / 1024).ToString("f2"),
                Extension = System.IO.Path.GetExtension(baseFile.FileName)
            };
            return outPut;
        }





        //public async Task CreateTag(CreateTagInPut input)
        //{
        //    var tag = tagRepository.GetAll().Where(x => x.Name == input.Name).FirstOrDefault();
        //    if (tag != null)
        //    {
        //        throw new Abp.UI.UserFriendlyException("系统提示", "标签已存在");
        //    }
        //    await tagRepository.InsertAsync(new Tag()
        //    {
        //        ProjectId = input.ProjectId,
        //        Name = input.Name
        //    });
        //}


        public List<KeyValuePair<string, int>> GetProjectTag(int projectId)
        {
            List<KeyValuePair<string, int>> result = new List<KeyValuePair<string, int>>();

            var list = GetPublicTag().Select(x => new KeyValuePair<string, int>(x, 1)).ToList();
            result.AddRange(list);

            var files = projectManager.projectDocmeutRepository.GetAll().Where(x => x.ProjectId == projectId && x.DocTypeId == 0).ToList();
            foreach (var item in files.Select(x => x.Tags))
            {
                if (!string.IsNullOrEmpty(item))
                {
                    List<string> tag = item.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                    foreach (var t in tag)
                    {
                        if (!list.Any(x => x.Key == t))
                        {
                            var outPut = new KeyValuePair<string, int>(t, 1);
                            result.Add(outPut);
                        }
                    }
                }
            }
            return result.Distinct().OrderBy(x => x.Key).ToList();
        }


        public List<GetFileTagOutPut> GetDocumentTag(int projectId)
        {
            List<GetFileTagOutPut> result = new List<GetFileTagOutPut>();
            var files = projectManager.projectDocmeutRepository.GetAll().Where(x => x.ProjectId == projectId && x.DocTypeId == 0).ToList();
            foreach (var item in files.Select(x => x.Tags))
            {
                if (!string.IsNullOrEmpty(item))
                {
                    List<string> tag = item.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                    foreach (var t in tag)
                    {
                        if (!result.Any(x => x.Key == t))
                        {
                            var outPut = new GetFileTagOutPut()
                            {
                                CreateId = 0,
                                Key = t,
                                Value = files.Count(x => x.Tags.Contains(t))
                            };
                            result.Add(outPut);
                        }
                    }
                }
            }
            foreach (var createId in files.Select(x => x.CreatorUserId))
            {
                if (!result.Any(x => x.CreateId == createId))
                {
                    var user = UserManager.Users.Where(x => x.Id == createId).SingleOrDefault();
                    var outPut = new GetFileTagOutPut()
                    {
                        CreateId = createId,
                        Key = user.Name,
                        Value = files.Count(x => x.CreatorUserId == createId)
                    };
                    result.Add(outPut);
                }
            }
            return result.OrderBy(x => x.Key).ToList();
        }


        public List<string> GetPublicTag()
        {
            List<string> result = new List<string>() {
"市场前景分析文件",
"专利布局文件",
"合成工艺分析",
"临床研究分析",
"生产可行性分析",
"政策可行性分析",
"项目SWOT分析",
"市场数据",
"项目评审文件",
"客户询盘",
"会议纪要",
"工艺筛选文件",
"原料试剂文件",
"分析方法",
"质量标准文件",
"杂质研究",
"送样单	",
"COA文件",
"参考文献",
"实验记录",
"成本核算",
"样品相关",
"周报",
"工艺评审报告",
"阶段简报",
"项目计划文件",
"合同",
"总结报告",
"移交文件",
"其他文件",
"会议纪要",
"技术包文件",
"工艺文件",
"原料试剂文件",
"分析方法",
"质量标准文件",
"杂质研究",
"中控检测文件",
"送样单",
"COA文件",
"参考文献",
"实验记录",
"成本核算",
"设备选型及需求",
"QRA资料",
"样品相关",
"周报",
"工艺评审报告",
"阶段简报",
"项目计划文件",
"合同",
"报批注册文件",
"批记录",
"工艺流程图 管道仪表图",
"安评文件 PSSR/PSRQ",
"三废处理",
"回收套用文件",
"项目问题跟踪表",
"Batch Tree",
"其他文件",
"会议纪要",
"总结报告",
"移交文件",
"仪器维护纪录",
"送样单",
"COA",
"实验记录",
"最终产物分析方法",
"中间体分析方法",
"最终产物质量研究",
"中间体质量研究",
"工艺稳定性研究",
"注册资料",
"质量标准文件",
"参考文献",
"阶段总结报告",
"会议纪要",
"其他",
"剂型选择",
"处方研究",
"工艺研究",
"实验记录",
"工艺评审报告",
"包装材料",
"原辅料控制",
"生产设备",
"成本核算",
"会议纪要",
"其他",
"申报资料转移",
"申报资料初审稿",
"正式申报材料",
"送寄资料",
"样品送检信息",
"快递信息",
"付费凭证",
"批文扫描件",
"现场核查资料",
"会议纪要",
"其他"};
            return result.Distinct().ToList();
        }





        public async Task GetFixedVersion(int documentId)
        {
            //var documentId = int.Parse(HttpContext.Current.Request.Form["documentId"]);
            var doc = await projectManager.projectDocmeutRepository.GetAsync(documentId);
            doc.IsFixedVersion = true;
            doc.VersionNo = (int)doc.VersionNo + 1.0;

            string str = string.Format("设置 {0}文档订版,版本号为{1}", doc.Name, doc.VersionNo);
            await operationLogManager.Create(documentId, str, HostOperation.文档, Newtonsoft.Json.JsonConvert.SerializeObject(doc), LogType.Doc定版);
        }


        public async Task SetDocumentTag(SetDocumentTagInPut input)
        {
            var doc = await projectManager.projectDocmeutRepository.GetAsync(input.DocumentId);
            doc.Tags = input.Tag;

            string str = string.Format("设置 {0}标签,标签为{1}", doc.Name, input.Tag);
            await operationLogManager.Create(input.DocumentId, str, HostOperation.文档, Newtonsoft.Json.JsonConvert.SerializeObject(doc), LogType.Doc标签);
        }


        public async Task RemoveDocumentVersion(int versionId)
        {
            var ver = projectManager.projectDocmeutVersionRepository.Get(versionId);
            await projectManager.projectDocmeutVersionRepository.DeleteAsync(versionId);

            string str = string.Format("删除 {0}版本,版本号为{1}", ver.Name, ver.Version);
            await operationLogManager.Create(ver.ProjectDocmeutId, str, HostOperation.文档, Newtonsoft.Json.JsonConvert.SerializeObject(versionId), LogType.Doc删除版本);
        }


        public async Task AddDocShare(DocShareInput input)
        {

            var userId = AbpSession.GetUserId();
            var doc = await projectManager.projectDocmeutRepository.GetAsync(input.DocId);

            var share = new Project.ProjectDocmeutShare()
            {
                CreationTime = DateTime.Now,
                CreatorUserId = userId,
                ProjectDocId = input.DocId,
                DocTypeId = doc.DocTypeId,
                EndDate = input.PlanFinshTime,
                ProjectId = input.ProjectId,
                Remark = input.Remark
            };
            share.Id = await projectDocmeutShareRepository.InsertAndGetIdAsync(share);
            foreach (var item in input.members)
            {
                var shareMember = new Project.ProjectDocmeutShareMember()
                {
                    ProjectShareDocId = share.Id,
                    UserId = item
                };
                await projectDocmeutShareMemberRepository.InsertAndGetIdAsync(shareMember);
            }

            var users = string.Join(",", UserManager.Users.Where(m => input.members.Contains(m.Id)).Select(q => q.Name));
            string str = string.Format("{0}设置共享，共享成员：{1}", doc.Name, users);
            await operationLogManager.Create(input.DocId, str, HostOperation.文档, Newtonsoft.Json.JsonConvert.SerializeObject(share), LogType.Doc分享);
        }

        public List<DocShareOutput> GetDocumentShare(int docId)
        {
            List<DocShareOutput> result = new List<DocShareOutput>();
            var shareDocIds = new List<int>();

            DateTime dtNow = DateTime.Now.Date;

            var shareLst = projectDocmeutShareRepository.GetAll().Where(x => x.ProjectDocId == docId).OrderByDescending(x => x.EndDate).ToList();

            foreach (var m in shareLst)
            {
                var shareMembers = projectDocmeutShareMemberRepository.GetAll().Where(x => x.ProjectShareDocId == m.Id).Select(x => x.User.Name).ToList();
                result.Add(new DocShareOutput()
                {
                    createBy = UserManager.Users.Where(x => x.Id == m.CreatorUserId).SingleOrDefault().Name,
                    createOn = m.CreationTime,
                    finishDate = m.EndDate,
                    shareId = m.Id,
                    shareTo = string.Join(",", shareMembers),
                    remark = m.Remark
                });
            }

            return result;
        }


        public async Task EndDocShare(int shareId)
        {
            var shareDoc = projectDocmeutShareRepository.Get(shareId);
            shareDoc.EndDate = System.DateTime.Now.Date.AddDays(-1);

            var users = string.Join(",", projectDocmeutShareMemberRepository.GetAll().Where(x => x.ProjectShareDocId == shareId).Select(m => m.User.Name));
            string str = string.Format("{0}收回共享，共享成员：{1}", shareDoc.Doc.Name, users);
            await operationLogManager.Create(shareDoc.Doc.Id, str, HostOperation.文档, Newtonsoft.Json.JsonConvert.SerializeObject(shareDoc), LogType.Doc收回);
        }

    }
}
